﻿
import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import { imageBaseUrl, downloadfun, isImageFile, queryURLParams, dealTime, easyCopy, IDeletePPEFile, getBrowserInfo } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {

    const generateh = (text, isShort) => {
        if (isShort) {
            return h('div', {
                style: "width:100px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis; -o-text-overflow: ellipsis;cursor:pointer"
            }, { default: () => text })
        } else {
            return h('div', {
                style: "width:300px;height:auto;"
            }, { default: () => text })
        }

    }

    const data = reactive({

        pdfOpen: false,
        pdfurl: "",
        checkPersonList: [

        ],

        messageTest: "",
        proxy: "",
        ccdetailInfo: {
            FormId: null, CurrentStatus: null,
        },
        loading:false,
        activeKey:1,
        urlParams: {},
        popShow: false,
        uploadLock:false,
        popTitle: '',
        imgUrl: "",
        previewShow: false,
        checkInfo: {
            advice: null,
            userinfo: null,
            date: null
        },
        removeIds:[],
        logList:[],
        approvalInfo: {
            advice: null,
            userinfo: null,
            date: null
        },
        areaList: [
            { label: '浦东', value: 1 },
            { label: '大场', value: 2 },
        ],
        detailColumns: [
            {
                title: '序号',
                dataIndex: 'no',
                key: 'no',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return (params.detailPagination.value.current - 1) * params.detailPagination.value.pageSize + index + 1
                },
            },
            {
                title: '姓名',
                dataIndex: 'name',
                key: 'name',
                align: 'center',
                customRender: ({ record }) => {
                    return `${record.name}(${record.code})`
                },
            },

            {
                title: '申请数量',
                dataIndex: 'number',
                key: 'number',
                align: 'center',

            },
            //{
            //    title: '状态',
            //    dataIndex: 'StatusName',
            //    key: 'StatusName',
            //    align: 'center',
            //    width: '100px',
            //    customRender: ({ record, text }) => {
            //        return h(antd.Tag, {
            //            color: "#457af7",
            //            style: 'cursor:pointer'
            //        }, { default: () => '待领取' });
            //    },

            //}
        ],
        typeId:"",
        detailDataSource: [],
        editInfoOptions: [],

        detailPagination: {
            total: 0,
            current: 1,
            loading: false,
            pageSize: 10,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗

        },

        editInfo: [{

            a: null,
            b: null,
            c: null,
            e: null,
            ceditInfoOptions: {},
            EmployeeList: []

        }],
        gg:"",
        cindex: 0,
        templateOpen: false,
        opType: 0,
        editUploadList: [],
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },
        itemRender: (data) => {

            let uid = data.file.uid
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })

            const FDBtn = h(antd.Popconfirm, {
                title: "确定删除此文件？确定后不可恢复",
                onConfirm: () => methods.btnDelete(data)

            }, { default: () => [deleteBtn]  })

            var btns = h('div', { style: "display:flex;margin-left:10px" }, {
                default: () => [
                    isImageFile(data.file.url) ? previewBtn : null,
                    downloadBtn,
                    params.urlParams.value.status == 1 ? FDBtn : null
                ]
            })
            return h('div', { style: 'margin-top:10px; width:400px;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        addParams: {
            name: null,
            code: null,
            number: null,
        },
        configData: {
            name1: "",
            name2: "",
            name3: "",
            name4: "",
            name5: "",
        },

    })
    let params = toRefs(data)
    const methods = {
        setVisible: (value) => {
            params.previewShow.value = value;
        },

        btnPreview: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url

                methods.setVisible(true)
            }
        },
        btnDownLoad: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            const { name, url } = item
            params.uploadLock.value = true
            downloadfun(name, url).finally(() => {
                params.uploadLock.value = false

            })
        },
        btnDelete: (e) => {
    
            const { FileId, uid } = e.file
            if (FileId) {

                IDeletePPEFile(Request, FileId).then(res => {
         
             
                    params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(es => es.uid != uid)

                    if (+params.urlParams.value.status == 1) {

                        let index = params.editUploadList.value.findIndex(e => e == FileId)
                        if (index != -1) {
                            params.editUploadList.value.splice(index,1)
                        }
       


                    }
                })
            }


        },
        ddownload: (name,url) => {
    
            downloadfun(name, url)
        },

        handleChange: (info) => {

            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('nfile', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: "/download/uploadfile?Path=PPE/Apply",
                    method: 'post',
                    data: formData
                }).then(res => {
                    params.uploadLock.value = false
                    let item = params.uploadImg.value.fileList.find(e => e.uid == res.Data[0].uid)
                    item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                    item.FileId = res.Data[0].FileId
                    item.FileName = res.Data[0].FileName
                    item.name = res.Data[0].FileName
                    if (+params.urlParams.value.status == 1) {
                        params.editUploadList.value.push(res.Data[0].FileId)


                    }
                })
            }

          

        

        },

        handlePopOk: () => {

            if (params.opType.value == 0) {
                params.editInfo.value[params.cindex.value].EmployeeList.push({
                    EmployeeNo: params.addParams.value.code,
                    EmployeeName: params.addParams.value.name,
                    Quantity: params.addParams.value.number,
                })
                params.editInfo.value[params.cindex.value].e = methods.sumData(params.editInfo.value[params.cindex.value].EmployeeList)
                params.addParams.value = {
                    name: null,
                    code: null,
                    number: null
                }
            } else {

            }

            params.popShow.value = false
        },
        handleSTypeChange: (a, b, c) => {
            let label = params.editInfo.value[b].AttrList[c].ItemList.filter(es => es.Id == a)[0].AttributeValue
            params.editInfo.value[b].AttrList[c].SelectLabel = label

        },
        handleTypeChange: (c, d) => {

            let item = params.editInfoOptions.value.filter(e => e.value == d.a)[0]
            params.editInfo.value[c].AttrList = item.AttrList
            params.editInfo.value[c].alabel = item.label
            params.editInfo.value[c].b = item.img
            params.editInfo.value[c].o = item.Description
            params.editInfo.value[c].p = item.Remark
            params.editInfo.value[c].c = item.unit
            params.editInfo.value[c].e = item.rnum
      


        },
        handleAdd: (i) => {
            params.opType.value = 0
            params.cindex.value = i
            params.popShow.value = true
            params.popTitle.value = `新增人员申请`
        },

        handleView: (e, i) => {

            if (!e.alabel || e.AttrList.filter(es => es.SelectLabel).length !== e.AttrList.length) {
                return params.messageTest.value.info('请先选择劳防用品和规格');
            }
            params.opType.value = 1
            params.popShow.value = true
            params.popTitle.value = `${e.alabel}(${e.AttrList.map(es => es.SelectLabel).join('/')})-人员申请详情`
            methods.getDetailTableList(true)
            params.cindex.value = i
        },

        addConfig: () => {
            params.editInfo.value.push({
                a: null,
                b: null,
                c: null,
                EmployeeList: [],
                ceditInfoOptions: {},
                e: null,
            })
        },
        delConfig: (i) => {
            console.log(i,'ii')

            let item = params.editInfo.value[i];

        
            if (item.Id) {
                params.removeIds.value.push(item.Id)
            }
   
            //removeIds
            params.editInfo.value.splice(i, 1)
        },
        filterOption: (val, type) => {
            return `${type.value}`.includes(`${val || ''}`)
        },
        handleCancel: () => {
            params.uploadImg.value.previewVisible = false;
            params.uploadImg.value.previewTitle = '';
        },
        getBase64: (file) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            })
        },
        handlePreview: async (file) => {
            console.log(file, 'file')
            if (!file.url && !file.preview) {
                file.preview = (await methods.getBase64(file.originFileObj));
            }
            params.uploadImg.value.previewImage = file.url || file.preview;
            params.uploadImg.value.previewVisible = true;
            params.uploadImg.value.previewTitle = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
        },



        enter: (index) => {
            params.cindex.value = index
        },



        handleDetailTableChange: (page) => {
            const { current, pageSize } = page
            params.detailPagination.value.current = current;
            params.detailPagination.value.pageSize = pageSize;
            methods.getDetailTableList()
        },

        getDetailTableList: (isRresh) => {
            params.detailPagination.value.loading = true
            if (isRresh) {
                params.detailPagination.value.current = 1
            }

            setTimeout(() => {
                params.detailDataSource.value = params.editInfo.value[params.cindex.value].EmployeeList.map(e => {
                    return {
                        name: e.EmployeeName,
                        code: e.EmployeeNo,
                        number: e.Quantity,

                    }
                })
                params.detailPagination.value.total = params.detailDataSource.value.length
                params.detailPagination.value.loading = false

            }, 500)

        },

        GetApplyFormNo: () => {
            Request({
                url: "/PPE/GetApplyFormNo",
                method: 'post',

            }).then(res => {
                params.configData.value.name1 = res.Data
            })

        },


        //sumData: (Array) => {
        //    let Sum = Array.reduce((Sum, currData) => {
        //        return Sum + currData.Quantity;
        //    }, 0)
        //    console.log(Sum)
        //    return Sum
        //},

        importData: (i) => {
            const input = document.createElement('input');
            input.type = 'file';
            input.addEventListener('change', function (event) {
                const file = event.target.files[0];
                var formdata = new FormData()
                formdata.append('any', file)
                Request({
                    url: "/PPE/ImportEmpList",
                    method: 'post',
                    data: formdata
                }).then(res => {
            
                    params.messageTest.value.info(res.Msg);
                    //params.editInfo.value[i].EmployeeList = res.Data
                    //params.editInfo.value[i].e = methods.sumData(params.editInfo.value[i].EmployeeList)



                })
            });
            input.click();

        },

        downloadTemplate: () => {
            downloadfun('人员申请模板', '../File/Templete/PPE/劳防用品申请人员导入模板.xls')
        },

        GetBasicList: () => {
           
            return new Promise((resolve, rej) => {
                Request({
                    url: "/PPE/GetBasicList",
                    method: 'post',
                    data: {
                        TypeId: params.urlParams.value.TypeId
                    }
                }).then(res => {
           
                    params.editInfoOptions.value = res.Data.map(e => {
                        return {
                            label: e.ProductName,
                            value: e.Id,
                            unit: e.Unit,
                            AttrList: e.AttrList,
                            rnum: 0,
                            Description: e.Description,
                            Remark: e.Remark,
                            img: e.ImagList && e.ImagList.map(es => {
                                return {
                                    url: es.url ? es.url : imageBaseUrl + es.FilePath.split('../..')[1],
                                    name: es.FileName,
                                    uid: es.uid,
                                    FileId: es.FileId
                                }
                            })
                        }
                    })
                    resolve(1)
                }).catch(err => {
                    rej(err)
                })
            })
  
        },
        IGetDepartmentApproverList: () => {
            return new Promise((resolve, rej) => {

                Request({
                    url: "/PPE/GetDepartmentApproverList",
                    method: 'post',

                }).then(res => {
                    params.checkPersonList.value = res.Data.map(e => ({ label: e.UserName, value: e.UserNo }))
                    if (params.checkPersonList.value.length != 0) {
                        params.configData.value.checkPersonId = params.checkPersonList.value[0].value
                    }
                    resolve(1)
                })



            })
        
        },
        GetPPEApplyDetail: (id) => {
            Request({
                url: "/PPE/GetPPEApplyDetail",
                method: 'post',
                data: {
                    Id:id
                }

            }).then(res => {
                params.loading.value = false
                params.ccdetailInfo.value.FormId = res.Data.Id
                params.ccdetailInfo.value.CurrentStatus = res.Data.Status
                console.log(res,'res')
                params.configData.value.name1 = res.Data.ApplyNo
                params.configData.value.name2 = `${res.Data.ApplyUserName}(${res.Data.ApplyUser})`
                params.configData.value.name3 = dealTime(res.Data.ApplyDate,'YYYY-MM-DD HH:mm')
                params.configData.value.name4 = res.Data.DepartmentName
                params.configData.value.name5 = res.Data.Remark
                //params.configData.value.name5 = res.Data.Remark
                //params.configData.value.name5 = res.Data.Remark
                //Description: e.Description,
                //    Remark: e.Remark,
                params.configData.value.FactoryAreaId = res.Data.FactoryAreaId
                params.configData.value.checkPersonId = res.Data.ApproveUser
                params.logList.value = res.Data.OperateLog

                params.editInfo.value = res.Data.ItemList.map(e => {

               
                    let AttrList = easyCopy(params.editInfoOptions.value.filter(es => es.value == e.BasicInfo.Id)[0].AttrList)

                    for (let index in e.AttrItemList) {
           
                        AttrList[index].Selected = e.AttrItemList[index].AttrItemId
                        AttrList[index].SelectLabel = e.AttrItemList[index].AttrItemName
                    }

                    return {
                        a: e.BasicInfo.Id,
                        Id: e.Id,
                        alabel: e.BasicInfo.ProductName,
                        AttrList: AttrList,
                        o: e.BasicInfo.Description,
                        p: e.BasicInfo.Remark,
                        b: e.BasicInfo.ImagList.map(es => {
                            return {
                                url: es.FilePath
                            }
                        }),
                        e: e.Quantity,
                        c:e.BasicInfo.Unit,
                    }

                })

                params.uploadImg.value.fileList = res.Data.FileList.map(e => {
                    return {
                        url: imageBaseUrl +e.FilePath.split('../..')[1],
                        FileId:e.FileId,
                        FileName: e.FileName,
                        name: e.FileName,
}
                })


               

            })
        },
   



        onSubmit: (Status) => {

            switch (+params.urlParams.value.status) {
               
                case 1:
                 //修改



      
                    let sModel =
                    {
                    "Id": params.urlParams.value.id,
                        "Status": Status,
                    FactoryAreaId: params.configData.value.FactoryAreaId,
                    "Remark": params.configData.value.name5,
                     "FileList": params.editUploadList.value,
                        "DeleteItemList": params.removeIds.value,
                        ApproveUser: params.configData.value.checkPersonId,
                     ItemList: params.editInfo.value.map(e => {
                         return {
                             BasicId: e.a,
                             FormId: params.urlParams.value.id,
                             Quantity: e.e,
                             AttrItemList: e.AttrList.map(es => {
                                 return {
                                     AttrItemId: es.Selected
                                 }
                             }),
                             Id: e.Id,
                         }
                     })
                    }



          

                    Request({
                        url: "/PPE/PPEApplyEdit",
                        method: 'post',
                        data: sModel
                    }).then(res => {
                        params.messageTest.value.info(res.Msg);
                        setTimeout(() => {
                            window.location.href = `/PPE/SupplyRequest?TypeId=${params.urlParams.value.TypeId}`
                        }, 1000)

                        params.editUploadList.value=[]
                    }).catch(err => {
                        params.messageTest.value.info('error');
                     
                    })


                    break;

                case 2:

                    let checkinfo = {
                        ...params.ccdetailInfo.value,
                        IsApprove: Status == 0 ? false : true,
                        Remark: params.checkInfo.value.advice
                    }
                    Request({
                        url: "/PPE/ApprovePPEApply",
                        method: 'post',
                        data: checkinfo
                    }).then(res => {
                        params.messageTest.value.info(res.Msg);
                        setTimeout(() => {
                            window.location.href = `/PPE/SupplyRequest?TypeId=${params.urlParams.value.TypeId}`
                        },1500)
   
               
                    }).catch(err => {
                 
                    })

            
                    //审核
                    break;
                case 3:

                    let approvalinfo = {
                        ...params.ccdetailInfo.value,
                        IsApprove: Status == 0 ? false : true,
                        Remark: params.approvalInfo.value.advice
                    }
                    Request({
                        url: "/PPE/ApprovePPEApply",
                        method: 'post',
                        data: approvalinfo
                    }).then(res => {
                        params.messageTest.value.info(res.Msg);
                        setTimeout(() => {
                            window.location.href = `/PPE/SupplyRequest?TypeId=${params.urlParams.value.TypeId}`
                        }, 1500)

                    }).catch(err => {

                    })


          //审批
                    break;
            }


            //let subOjb = {
            //    ApplyNo: params.configData.value.name1,
            //    Remark: params.configData.value.name5,
            //    Status: Status,
            //    FileList: params.uploadImg.value.fileList.map(e => e.FileId),
            //    BasicList: params.editInfo.value.map(e => {
            //        return {
            //            BasicId: e.a,
            //            AttrItemsId: e.AttrList.map(es => es.Selected),
            //            EmployeeList: e.EmployeeList,
            //        }
            //    })
            //}
            //Request({
            //    url: "/PPE/PPEApply",
            //    method: 'post',
            //    data: subOjb

            //}).then(res => {
            //    params.messageTest.value.info(res.Msg);

            //})




        },
        onBack: () => {
            window.history.back(-1)
        },
        sdealTime: (val) => {
            return dealTime(val,'YYYY-MM-DD HH:mm')
        },
 
        init: () => {
              getBrowserInfo().catch(err => { console.log(err)})
            if (proxy) {

                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });

            params.urlParams.value = queryURLParams()


            params.loading.value = true

            params.uploadLock.value = true

            
        
            setTimeout(() => {
                let info = Storage.get('AccountInfo', true)

                switch (+params.urlParams.value.status) {

                    case 1:
                        //修改
                        break;
                    case 2:
                        
                        params.checkInfo.value.userinfo = `${info.UserName}(${info.UserNo})`
                        params.checkInfo.value.date = dayjs(Date.now()).format('YYYY-MM-DD HH:mm')


                        //审核
                        break;
                    case 3:
                        params.approvalInfo.value.userinfo = `${info.UserName}(${info.UserNo})`
                        params.approvalInfo.value.date = dayjs(Date.now()).format('YYYY-MM-DD HH:mm')
                        //审批
                        break;
                }

                Request({
                    url: "/Account/createJwtToken",
                    method: 'post',
                    data: {
                        "userName": info && info.UserNo
                    }
                }).then(res => {
                    Storage.set('token', res.Data,true)
                    methods.IGetDepartmentApproverList().then(ress => {
                        if (params.urlParams.value.status) {
                            methods.GetBasicList().then(res => {
                                methods.GetPPEApplyDetail(params.urlParams.value.id)
                                params.loading.value = false
                                params.uploadLock.value = false
                            })




                        } else {
                            params.configData.value.name2 = `${info.UserName}(${info.UserNo})`
                            params.configData.value.name3 = dayjs(Date.now()).format('YYYY-MM-DD HH:mm')
                            params.configData.value.name4 = info.DepartmentName
                            methods.GetBasicList()
                            methods.GetApplyFormNo()
                            params.loading.value = false
                            params.uploadLock.value = false


                        }
                    })
              
           

                })
            },1200)
    
        },

    }
    const template = {

        pdfPopModel: {
            template: `
           <a-modal v-model:open="pdfOpen" width = "80%" title = "PDF预览" v-on:ok="pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="pdfurl" type="application/pdf" width="100%" style="height:100%;" />

</div>
  
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },


        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end pr-4">
                    <a-space>              
  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(0)"

  >
  <a-button v-if='urlParams.status==1'  type="dashed">保存</a-button>
  </a-popconfirm>

  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(1)"
  >
  <a-button  v-if='urlParams.status==1' type="primary">提交</a-button>
  </a-popconfirm>

  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(0)"
  >
          <a-button v-if='[2,3].includes(+urlParams.status)' type="primary" danger>驳回</a-button>
  </a-popconfirm>

  <a-popconfirm
   title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(1)"
  >
          <a-button  v-if='[2,3].includes(+urlParams.status)'  type="primary">同意</a-button>
  </a-popconfirm>

              
              
                        <a-button v-on:click="onBack">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition